<?php

namespace App\Crontab;

use App\Logic\Member\MemberProfitScoreService;
use App\Logic\Member\MemberScoreService;
use App\Process\Task;
use App\Util\CommonHelper;
use App\Event\Event;
use \EasySwoole\Crontab\JobInterface;
use EasySwoole\EasySwoole\Config;

class TaskMinute implements JobInterface
{
    public function jobName(): string
    {
        // 定时任务的名称
        return 'taskMinute';
    }

    public function crontabRule(): string
    {
        // 定义执行规则 根据Crontab来定义
        return '*/1 * * * *';
    }

    public function run()
    {
        //防止多台机器重复执行
//        if(false === TaskExclusive::lock(__CLASS__ . ':' . __FUNCTION__))return false;
        // 定时任务的执行逻辑
        $delay = 1;

        \EasySwoole\Component\Timer::getInstance()->after($delay*1000, function() use($delay){
            try{
                if (true || Config::getInstance()->getConf('ENV') == 'produce') {
                    /**每日自动结算*/
                    Task::orderAutoSettle();
                    //自动统计用户订单数和收益
                    Task::memberOrderCount();
                    //自动统计用户收益
                    Task::memberProfitCount();
                    //自动统计每日订单任务汇总
                    Task::orderTaskStatistics();
                    //自动更新订单状态 SHIPPED:已发货;
                    Task::orderStateShipped();
                    //自动更新订单状态 RECEIPT:确认收货;
                    Task::orderStateReceipt();
                    /**统计所有帐户和订单*/
                    Task::statisticsAll();
                }
            }catch (\Throwable $e){
                CommonHelper::logException($e);
            }
            \EasySwoole\EasySwoole\Logger::getInstance()->info('定时任务执行成功: ' . date('Y-m-d H:i:s', time() + $delay));
        });

        ++$delay;
        return true;
    }

    public function onException(\Throwable $throwable)
    {
        // 捕获 run 方法内所抛出的异常
    }

}
